import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { ConfigProvider, Tabs } from 'antd';
import type { TabsProps } from 'antd';
import { useLocation } from 'react-router-dom';
import { useNav } from '../nav';
import { useIntl } from '@/components/locale';
import { useRootConfig } from '@/components/root-config';
import './index.less';

function getMenuItemByKey(menus: TabsProps['items'], key: string): any {
    let res = null;
    if (menus?.length) {
        for (let i = 0; i < menus.length; i += 1) {
            const { children, key: path } = menus[i];

            if (children instanceof Array) {
                res = getMenuItemByKey(children, key);
            } else if (path === key) {
                res = menus[i];
            }
            if (res) {
                break;
            }
        }
    }
    return res;
}

// tabs
function Breadcrumb({ menus = [] }: { menus: TabsProps['items'] }) {
    const intl = useIntl();
    const { panes, navTo, nav, closePane } = useNav();
    const { theme } = useRootConfig();
    const { pathname } = useLocation();

    const activePaneKey = useMemo(() => pathname.replace(/\/portal\/?/i, '') || 'home', [pathname]);

    const initRef = useRef(false);
    // const [initialized, setInitialized] = useState(false);

    // 面板页签多语
    const items = useMemo(
        () =>
            panes.map((item) => ({
                ...item,
                label: item.langID
                    ? intl.formatMessage({
                          id: item.langID,
                          defaultMessage: item.label,
                      })
                    : item.label,
            })),
        [panes, intl],
    );

    // 手动刷新页面时，打开当前路由对应的页签
    useEffect(() => {
        if (initRef.current) return;
        if (menus.length > 0) {
            initRef.current = true;
            const menuItem = getMenuItemByKey(menus, activePaneKey);
            if (menuItem) {
                nav({
                    key: menuItem.key,
                    langID: menuItem.langID,
                    label: menuItem.label,
                    options: {
                        replace: true,
                    },
                });
            }
        }
    }, [menus, activePaneKey, nav]);

    // 切换页签
    const onChange = useCallback(
        function onChange(key: string) {
            navTo(key);
        },
        [navTo],
    );

    // 关闭页签
    const onEdit = useCallback(
        function onEdit(targetKey: React.MouseEvent | React.KeyboardEvent | string, action: 'add' | 'remove') {
            if (action === 'remove') {
                closePane(targetKey as string);
            }
        },
        [closePane],
    );

    //
    const lightTheme = {
        components: {
            Tabs: {
                cardBg: '#f8fafc',
                cardGutter: 1,
                cardHeight: 30,
                cardPaddingSM: '4px 8px',
                titleFontSizeSM: 12,
                horizontalMargin: '0 0 0 0',
                horizontalItemPaddingSM: '0 0',
            },
        },
    };

    const darkTheme = {
        token: {
            colorBgContainer: '#001529',
        },
        components: {
            Tabs: {
                cardBg: '#172b4d',
                cardGutter: 1,
                cardHeight: 30,
                cardPaddingSM: '4px 8px',
                titleFontSizeSM: 12,
                horizontalMargin: '0 0 0 0',
                horizontalItemPaddingSM: '0 0',
                itemColor: 'rgba(255, 255, 255, 0.65)',
            },
        },
    };

    return (
        <ConfigProvider theme={theme === 'dark' ? darkTheme : lightTheme}>
            <Tabs
                hideAdd
                activeKey={activePaneKey}
                type='editable-card'
                items={items}
                size='small'
                className='breadcrumb-tabs'
                onEdit={onEdit}
                onChange={onChange}
            />
        </ConfigProvider>
    );
}

export default Breadcrumb;
